package com.bto.solar.work.lease;

import com.alibaba.fastjson2.JSONObject;
import com.bto.solar.work.common.BizException;
import com.bto.solar.work.dao.ICustomerService;
import com.bto.solar.work.dao.ILeaseReviewService;
import com.bto.solar.work.dao.IOrderBaseService;
import com.bto.solar.work.dto.lease.ContractFileRes;
import com.bto.solar.work.dto.lease.FileAndContactAsyncPushRes;
import com.bto.solar.work.dto.lease.FileContractPushBody;
import com.bto.solar.work.dto.lease.InsuranceRenewalBody;
import com.bto.solar.work.dto.lease.LeaseApprovalNotifyReq;
import com.bto.solar.work.dto.lease.LeaseApprovaledNotifyResp;
import com.bto.solar.work.dto.lease.OperatingBody;
import com.bto.solar.work.dto.lease.OperatingFarmGinsReqBody;
import com.bto.solar.work.dto.lease.OperatingFarmGinsRes;
import com.bto.solar.work.dto.lease.OperatingRes;
import com.bto.solar.work.dto.lease.OperatingSignBody;
import com.bto.solar.work.dto.lease.OperatingStatusQueryBody;
import com.bto.solar.work.dto.lease.OperatingStatusQueryRes;
import com.bto.solar.work.dto.lease.PowerSellOlFIleBody;
import com.bto.solar.work.dto.lease.TenantPreAuditBody;
import com.bto.solar.work.dto.lease.YsxxResultRes;
import com.bto.solar.work.entity.Customer;
import com.bto.solar.work.entity.LeaseReview;
import com.bto.solar.work.entity.OrderBase;
import com.bto.solar.work.utils.NullUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class LeaseApi {

    public static Logger log = LoggerFactory.getLogger(LeaseApi.class);

    @Autowired
    private LeaseService leaseService;
    @Autowired
    @Lazy
    private ICustomerService customerService;
    @Autowired
    @Lazy
    private IOrderBaseService orderService;
    @Autowired
    private ILeaseReviewService leaseReviewService;

    /**
     * 6-01 承租人预审
     */
    public boolean pushCustomerPreApproval(OrderBase orderBase){
        String name = "承租人基础信息同步";
        String bizCode = "FINANCE_PROJECT_TENANT";
        String  tenantPreAuditUrl = "/r/api/finance/sync/project/tenant";
        TenantPreAuditBody body = leaseService.buildTenantPreAuditBody(orderBase);
        try {
            String response = leaseService.sendHttpsRequestLease(tenantPreAuditUrl, null, bizCode, body);
            return leaseService.checkLeaseResponseOk(response);
        }
        catch (BizException e){
            return false;
        }
    }

    /**
     *  6-02 承租人预审状态查询 (预审状态查询)
     */
    public YsxxResultRes getTenantPreAuditState(OrderBase orderBase){
        String name = "承租人预审状态同步";
        String bizCode = "FINANCE_PROJECT_TENANT_STATUS";
        String  getTenantPreAuditStateUrl = "/r/api/finance/project/tenant/status/query";
        JSONObject body = new JSONObject();
        //客户身份证号
        Customer customer = customerService.getById(orderBase.getCustomerId());
        body.put("idCardNo" , customer.getIdNumber());
        try {
            String response = leaseService.sendHttpsRequestLease(getTenantPreAuditStateUrl, null, bizCode, body);
            if(leaseService.checkLeaseResponseOk(response)){
                return JSONObject.parseObject(response).getJSONArray("body").getJSONObject(0).to(YsxxResultRes.class);
            }
            return null;
        }
        catch (BizException e){
            log.error("{} {} 请求失败" ,name , getTenantPreAuditStateUrl  );
            return null;
        }
    }

    /**
     *  6-03 进件信息同步
     */
    public OperatingRes operating(OrderBase orderBase) {
        String name = "进件同步";
        String bizCode = "FINANCE_PROJECT_OL";
        String  url = "/r/api/finance/sync/project/operating/lease";
        OperatingBody body = leaseService.buildOperatingBody(orderBase);
        try {
            String response = leaseService.sendHttpsRequestLease(url, null, bizCode, body);
            if(leaseService.checkLeaseResponseOk(response)){
                return JSONObject.parseObject(response).getJSONArray("body").getJSONObject(0).to(OperatingRes.class);
            }
            return null;
        }
        catch (BizException e){
            log.error("{} {} 请求失败" ,name , url  );
            return null;
        }
    }

    /**
     * 6-04 农户投放审查信息同步
     */
    public JSONObject operatingSign(OrderBase orderBase, boolean isSGFinished){
        String name = "农户投放审查信息同步";
        String bizCode = "FINANCE_PROJECT_OL_SIGN";
        String  url = "/r/api/finance/sync/project/operating/lease/sign";
        OperatingSignBody body = leaseService.buildOperatingSignBody(orderBase, isSGFinished);
        try {
            String response = leaseService.sendHttpsRequestLease(url, null, bizCode, body);
            if(leaseService.checkLeaseResponseOk(response)){
                return JSONObject.parseObject(response).getJSONArray("body").getJSONObject(0);
            }
            return null;
        }
        catch (BizException e){
            log.error("{} {} 请求失败" ,name , url);
            return null;
        }
    }

    /**
     * 6-04-01 并网及商务信息更新
     */
    public JSONObject operatingSignUpdate(OrderBase orderBase){
        String name = "农户投放审查信息同步";
        String bizCode = "FINANCE_PROJECT_OL_SIGN_UPDATE";
        String  url = "/r/api/finance/ol/sync/sign/update";
        OperatingSignBody body = leaseService.buildOperatingSignUpdateBody(orderBase);
        try {
            String response = leaseService.sendHttpsRequestLease(url, null, bizCode, body);
            if(leaseService.checkLeaseResponseOk(response)){
                return JSONObject.parseObject(response).getJSONArray("body").getJSONObject(0);
            }
            return null;
        }
        catch (BizException e){
            log.error("{} {} 请求失败" ,name , url);
            return null;
        }
    }

    /**
     * 6-05 经营租赁资料与合同推送 - 同步
     */
    public JSONObject fileAndContactSyncPush(OrderBase orderBase, List<String> types, boolean isLeaseSyncProject){
        String name = "经营租赁资料与合同推送";
        String bizCode = "FINANCE_OL_FILE";
        String  url = "/r/api/finance/ol/sync/file";
        FileContractPushBody body = leaseService.buildFileAndContactPushBody(orderBase, types, isLeaseSyncProject);
        try {
            String response = leaseService.sendHttpsRequestLease(url, null, bizCode, body);
            if(leaseService.checkLeaseResponseOk(response)){
                return JSONObject.parseObject(response).getJSONArray("body").getJSONObject(0);
            }
            return null;
        }
        catch (BizException e){
            log.error("{} {} 请求失败" ,name , url);
            return null;
        }
    }



    /** 6-06
     * 农户单据状态查询
     */
    public OperatingStatusQueryRes operatingStatusQuery(String orderId){
        String name = "农户单据状态查询";
        String bizCode = "FINANCE_PROJECT_OL_STATUS";
        String  url = "/r/api/finance/project/operating/lease/status/query";
        OperatingStatusQueryBody body = new OperatingStatusQueryBody();
        OperatingStatusQueryBody.PrjDocumentStatusDtoDTO prjDocumentStatus = new OperatingStatusQueryBody.PrjDocumentStatusDtoDTO();

        //进件序号 -- 订单Id
        prjDocumentStatus.setPartnersContractNumber(orderId);

        body.setPrjDocumentStatusDto(prjDocumentStatus);
        try {
            String response = leaseService.sendHttpsRequestLease(url, null, bizCode, body);
            if(leaseService.checkLeaseResponseOk(response)){
                return JSONObject.parseObject(response).getJSONArray("body").getJSONObject(0).to(OperatingStatusQueryRes.class);
            }
            return null;
        }
        catch (BizException e){
            log.error("{} {} 请求失败" ,name , url);
            return null;
        }
    }



    /** 6-07
     * 农户收益查询
     */
    public OperatingFarmGinsRes operatingFarmFainsQuery(OrderBase orderBase, OperatingFarmGinsReqBody.OlDocumentFarmGainsDto req){
        String name = "农户收益查询";
        String bizCode = "FINANCE_PROJECT_OL_GAINS";
        String  url = "/r/api/finance/project/operating/lease/farm/gains";
        OperatingFarmGinsReqBody body = new OperatingFarmGinsReqBody();
        body.setOlDocumentFarmGainsDto(req);
        try {
            String response = leaseService.sendHttpsRequestLease(url, null, bizCode, body);
            if(leaseService.checkLeaseResponseOk(response)){
                return JSONObject.parseObject(response).getJSONArray("body").getJSONObject(0).to(OperatingFarmGinsRes.class);
            }
            return null;
        }
        catch (BizException e){
            log.error("{} {} 请求失败" ,name , url);
            return null;
        }
    }

    /** 9
     * 租后购售电合同推送
     * 此处要返回推送的结果 ， 不是直接抛异常
     * 如果该任务执行失败，做记录，不影响整体流程
     */
    public boolean powerSellOlFileContractPushLease(OrderBase orderBase){
        String name = "租后购售电合同补充推送";
        String bizCode = "FINANCE_POWER_SELL_OL_FILE";
        String  psOlContractPush = "/r/api/finance/ol/power/sell/file";
        PowerSellOlFIleBody body = leaseService.buildPowerSellOlFileBody(orderBase);
        try {
            String response = leaseService.sendHttpsRequestLease(psOlContractPush, null, bizCode, body);
            return leaseService.checkLeaseResponseOk(response);
        }
        catch (BizException e){
            return false;
        }
    }

    /** 10
     * 合同文本获取
     */
    public ContractFileRes getContractFile(OrderBase orderBase){
        String name = "合同文本获取";
        String bizCode = "FINANCE_CONTRACT_FILE_GET";
        String  url = "/r/api/finance/contract/file/get";
        JSONObject body = new JSONObject();
        //进件序号 -- 订单ID
        body.put("partnersContractNumber" , orderBase.getOrderId());
        try {
            String response = leaseService.sendHttpsRequestLease(url, null, bizCode, body);
            if(leaseService.checkLeaseResponseOk(response)){
                return JSONObject.parseObject(response).getJSONArray("body").getJSONObject(0).to(ContractFileRes.class);
            }
            return null;
        }
        catch (BizException e){
            log.error("{} {} 请求失败" ,name , url);
            return null;
        }
    }

    /**  11
     *  经营租赁资料与合同推送  - 异步
     */
    public JSONObject fileAndContactAsyncPush(OrderBase orderBase, List<String> types, boolean isLeaseSyncProject){
        String name = "附件异步推送";
        String bizCode = "FINANCE_OL_ASYNC_FILE";
        String  url = "/r/api/finance/ol/async/file";
        FileContractPushBody body = leaseService.buildFileAndContactPushBody(orderBase, types, isLeaseSyncProject);
        try {
            String response = leaseService.sendHttpsRequestLease(url, null, bizCode, body);
            if(leaseService.checkLeaseResponseOk(response)){
                return JSONObject.parseObject(response).getJSONArray("body").getJSONObject(0);
            }
            return null;
        }
        catch (BizException e){
            log.error("{} {} 请求失败" ,name , url);
            return null;
        }
    }

    public JSONObject fileAndContactAsyncPush(String orderId , List<String> types, boolean isLeaseSyncProject){
        OrderBase orderBase = orderService.getById(orderId);
        if (orderBase == null) {
            throw new BizException("订单{}不存在, 无法进行资料推送！", orderId);
        }
        return fileAndContactAsyncPush(orderBase, types, isLeaseSyncProject);
    }

    public boolean isFileAndContactSyncPush(OrderBase orderBase , List<String> types, boolean isLeaseSyncProject){
        return leaseService.checkLeaseSyncPushResponseOk(fileAndContactSyncPush(orderBase, types, isLeaseSyncProject));
    }

    public boolean isFileAndContactSyncPush(String orderId , List<String> types, boolean isLeaseSyncProject){
        OrderBase orderBase = orderService.getById(orderId);
        if (NullUtils.isNull(orderBase)) {
            throw new BizException("订单{}无法找到，推送越秀资料失败！", orderId);
        }
        return leaseService.checkLeaseSyncPushResponseOk(fileAndContactSyncPush(orderBase, types, isLeaseSyncProject));
    }

    /**  12
     *   附件异步结果查询
     */
    public FileAndContactAsyncPushRes fileAndContactAsyncPushResult(String queryId){
        String name = "附件异步结果查询";
        String bizCode = "FINANCE_OL_ASYNC_FILE_QUERY";
        String  url = "/r/api/finance/ol/async/file/query";
        JSONObject body = new JSONObject();
        body.put("queryId" , queryId);
        try {
            String response = leaseService.sendHttpsRequestLease(url, null, bizCode, body);
            if(leaseService.checkLeaseResponseOk(response)){
                return JSONObject.parseObject(response).getJSONArray("body").getJSONObject(0).to(FileAndContactAsyncPushRes.class);
            }
            return null;
        }
        catch (BizException e){
            log.error("{} {} 请求失败" ,name , url);
            return null;
        }
    }

    /**
     * 保险续保信息推送
     */
    public ContractFileRes insuranceRenewal(OrderBase orderBase){
        String name = "保险续保信息推送";
        String bizCode = "LEASE_ITEM_RENEWAL";
        String  url = "/r/api/lease/item/renewal";
        InsuranceRenewalBody body = leaseService.buildInsuranceRenewal(orderBase);
        try {
            String response = leaseService.sendHttpsRequestLease(url, null, bizCode, body);
            if(leaseService.checkLeaseResponseOk(response)){
                return JSONObject.parseObject(response).getJSONArray("body").getJSONObject(0).to(ContractFileRes.class);
            }
            return null;
        }
        catch (BizException e){
            log.error("{} {} 请求失败" ,name , url);
            return null;
        }
    }

    /**
     * 通过查询单据来同步订单状态
     */
    public void updateLeaseStateToBtoState(String orderId) {
        OrderBase orderBase = orderService.getById(orderId);
        if (orderBase == null) {
            throw new BizException("同步订单{}不存在", orderId);
        }
        OperatingStatusQueryRes res = operatingStatusQuery(orderBase.getOrderId());
        if (res != null) {
            syncApprovalLeaseStatusAndLeaseRiew(orderBase, res);
        }
    }

    /**
     * 同步资方状态并且记录资方
     */
    public void syncApprovalLeaseStatusAndLeaseRiew(OrderBase orderBase,  OperatingStatusQueryRes res) {
        LeaseApprovalNotifyReq.PrjProjectOperatingLeaseStatus prjProjectOperatingLeaseStatus = new LeaseApprovalNotifyReq.PrjProjectOperatingLeaseStatus();
        BeanUtils.copyProperties(res.getPrjProjectOperatingLeaseStatus(), prjProjectOperatingLeaseStatus);
        try {
            leaseService.decideLeaseStateToBtoState(orderBase, prjProjectOperatingLeaseStatus);
            //记录审核记录
            LeaseReview leaseReview = new LeaseReview();
            BeanUtils.copyProperties(prjProjectOperatingLeaseStatus, leaseReview);//状态信息
            leaseReview.setOrderId(orderBase.getOrderId());//订单ID
            leaseReview.setBusinessKey(res.getBusinessKey());//身份证或者订单ID
            LeaseReview leaseReviewByDb = leaseReviewService.lambdaQuery().eq(LeaseReview::getOrderId, orderBase.getOrderId()).one();
            if (null != leaseReviewByDb) {
                leaseReview.setLeaseReviewId(leaseReviewByDb.getLeaseReviewId());//主键ID
            }
            leaseReviewService.saveOrUpdate(leaseReview);
        } catch (Exception e) {
            throw new BizException("单据状态同步失败！" + e.getMessage());
        }
    }

    /**
     * 越秀主动推送同步订单状态
     */
    public LeaseApprovaledNotifyResp syncApprovalLeaseStatus(LeaseApprovalNotifyReq leaseApprovaledNotifyReq) {
        return leaseService.syncApprovalLeaseStatus(leaseApprovaledNotifyReq);
    }
}
